package com.yanghui.lingyue.functions.apiBase

import com.icedata.sika.bridge.*
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.Sika
import com.icedata.sika.util.Logger
import com.yanghui.lingyue.data.Command
import com.yanghui.lingyue.functions.AbstractFunction
import com.yanghui.lingyue.functions.python.GetSatellitePosition
import com.yanghui.lingyue.utils.functionUtils.FunctionUtils
import com.yanghui.lingyue.utils.netUtils.HttpJsonUtils
import com.yanghui.lingyue.utils.netUtils.NetImageUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStream

import java.util.*

object SendMoePictures: AbstractFunction() {

    private val pictureURLS = LinkedList<PictureURL>()
    override val name: String = "MoePic"

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent) return command
        event as SikaGroupEvent
        if (!FunctionUtils.atBot(event)) return command
        if (event.sendGroup.id !in enableGroup) return command
        val param = FunctionUtils.extractKeyword(event, "艺术")
        param?.let {
            command.add(Command(event, name, it))
        }
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        if (command.param.contains("多来点")) {
            repeat(3) {
                sendPicture(command.sendGroup!!)
            }
        } else {
            sendPicture(command.sendGroup!!)
        }
        return CommandProcessor.Result.ADOPT
    }

    override fun filter(command: Command): Boolean {
        return command.instruction.contains(name)
    }

    init {
        pictureURLS.add(PictureURL("https://api.ixiaowai.cn/api/api.php").apply {
            this.getMethod = { this.url }
        })
        pictureURLS.add(
            PictureURL(
                HttpJsonUtils.addStringParamMethodGet(
                    "https://api.vvhan.com/api/acgimg",
                    "return",
                    "json"
                )
            ).apply {
                this.getMethod = {
                    HttpJsonUtils.getJsonObjectFromURLMethodGet(this.url).getString("imgurl")
                }
            }
        )
        pictureURLS.add(
            PictureURL(
                HttpJsonUtils.addStringParamMethodGet(
                    "https://www.dmoe.cc/random.php",
                    "return",
                    "json"
                )
            ).apply {
                this.getMethod = {
                    HttpJsonUtils.getJsonObjectFromURLMethodGet(this.url).getString("imgurl")
                }
            })
        pictureURLS.add(
            PictureURL("https://img.xjh.me/random_img.php").apply {
                this.getMethod = {
                    val params = HashMap<String, String>()
                    params["return"] = "json"
                    params["type"] = "bg"
                    params["ctype"] = "acg"
                    HttpJsonUtils.getJsonObjectFromURLMethodGet(
                        HttpJsonUtils.addAllStringParamMethodGet(this.url, params)
                    ).getString("img")
                }
            }
        )
        pictureURLS.add(
            PictureURL(
                HttpJsonUtils.addStringParamMethodGet(
                    "https://www.rrll.cc/tuceng/ecy.php",
                    "return",
                    "json"
                )
            ).apply {
                this.getMethod = {
                    HttpJsonUtils.getJsonObjectFromURLMethodGet(this.url).getString("acgurl")
                }
            }
        )
        pictureURLS.add(PictureURL("https://api.yimian.xyz/img").apply {
            this.getMethod = {
                val params = HashMap<String, String>()
                params["type"] = "moe"
                params["size"] = "1920x1080"
                HttpJsonUtils.getStringFromURLMethodGet(
                    HttpJsonUtils.addAllStringParamMethodGet(this.url, params)
                ) ?: ""
            }
        })
    }

    suspend fun sendPicture(contact: SikaGroupContact) {
        var inputStream: InputStream? = null
        GlobalScope.launch(Dispatchers.IO) {
            var count = 5
            while (true) {
                try {
                    val num = Random().nextInt(pictureURLS.size)
                    val url = pictureURLS[num].getImageUrl()
                    if (url.isBlank())
                        continue
                    Logger.logDebug("GetImage", pictureURLS[num].url)
                    count--
                    inputStream = NetImageUtils.getImageFromURL(url)
                    break
                } catch (e: Exception) {
                    if (count <= 0)
                        break
                }
            }
            inputStream?:contact.sendMessage("图片下载错误")
            inputStream?:return@launch
            val builder = SikaMessageChainBuilder()
            try {
                builder.add(SikaImageMessage.build(inputStream!!, contact, SikaImageMessage.JPG))
                contact.sendMessage(builder)
            } catch (e: NullPointerException) {
                contact.sendMessage("图片下载错误")
            }
        }
    }

    private class PictureURL(val url: String) {
        var getMethod: () -> String = { "" }
        fun getImageUrl(): String {
            return getMethod()
        }
    }
}